
package xyz.eden.boot.ability.code.generate;

import freemarker.cache.FileTemplateLoader;
import freemarker.cache.StringTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.CharEncoding;
import xyz.eden.boot.ability.code.generate.enums.TemplateEngineType;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
import java.util.Objects;

@Slf4j
public class FreemarkerTemplateFromFile implements TemplateFactory {

    private static Configuration configuration;

    @Override
    public void initTemplateEngine() throws IOException {
        Configuration c = new Configuration(Configuration.VERSION_2_3_30);
        TemplateLoader templateLoader = new FileTemplateLoader(new File(""));
        c.setTemplateLoader(templateLoader);
        c.setDefaultEncoding(CharEncoding.UTF_8);
        configuration = c;
    }

    @Override
    public boolean isSupper(TemplateEngineType engineType) {
        return Objects.equals(TemplateEngineType.FREEMARKER_FILE, engineType);
    }

    @Override
    public String processTemplate(String templateStr, Map<String, Object> dataMap) {
        try {
            StringWriter stringWriter = new StringWriter();
            Template template = new Template("hello", templateStr, configuration);
            template.process(dataMap, stringWriter);
            return stringWriter.toString();
        } catch (Exception e) {
            log.error("FreemarkerTemplateFromText.processTemplate - template process exception.", e);
            return templateStr;
        }
    }
}
